package com.example.administrator.weipiao;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 负责访问网络的工具
 * Created by Administrator on 2016/9/10.
 */
public class HttpUtil {
    public static byte[] loadData(String path) throws IOException {
        URL url = new URL(path);
        try {
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            if (conn.getResponseCode()==200){
                InputStream is = conn.getInputStream();
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                int len = 0;
                byte[] buffer = new byte[1024];
                while ((len=is.read(buffer))!=-1){
                    baos.write(buffer,0,len);
                    baos.flush();
                }
                byte[] data = baos.toByteArray();
                is.close();
                baos.close();
                return data;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }
}
